class CommonController < ApplicationController

	before_action :current_admin,except: [:new, :create, :register, :do_register]

	def index
		@user = @current_user
	end
	# 登录页面
	def new
		 @user = User.new
	end
	#提交登录信息
	def create
		@user = User.where(username: params[:user][:username]).first
		if @user && @user.password == params[:user][:password]
			session[:user_id] = @user.id
			remember @user
			redirect_to(action: 'index',controller: 'posts')
		else
			flash[:error] = '用户名或密码错误'
			render 'new'
		end

	end

	def destroy
		forget(current_user)
		redirect_to(action: :index,controller: 'posts')
	end

	def register
		@user = User.new
	end

	def do_register
		password_confirmation = params[:user][:password_confirmation]
		@user = User.new(user_register_params)
		respond_to do |format|
			if  password_confirmation == @user.password && @user.save
				session[:user_id] = @user.id
				format.html { redirect_to  action: :index, notice: 'User was successfully created.' }
				format.json { render :index, status: :created, location: @user }
			else
				flash[:error] = '密码不一致'
				format.html { render :register }
				format.json { render json: @user.errors, status: :unprocessable_entity }
			end
		end
	end

	def user_register_params
		params.require(:user).permit(:name, :email, :password, :username)
	end

	#忘记用户
	def forget(user)
		user.forget
		cookies.delete(:user_id)
		cookies.delete(:remember_token)
	end

end
